using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace cswavrec
{

    public class AudioRecorder_NotForVista
    {

        #region "Private properties, events and fields"

        private const int m_Size = 100 * 1024 * 1024;
        private static byte[] m_Buffer = new byte[m_Size];
        private static int m_Tail = 0;
        private static WaveLib.WaveInRecorder m_Recorder = null;

        #endregion

        #region "Public properties, events and fields"

        public static int Length
        {
            get
            {
                return m_Tail;
            }
        }

        #endregion

        #region "Constructors"

        #endregion

        #region "private methods"

        private static void DataArrived(IntPtr data, int size)
        {
            if (m_Recorder == null) return;

            if (m_Tail + size <= m_Size)
            {
                System.Runtime.InteropServices.Marshal.Copy(data, m_Buffer, m_Tail, size);
                m_Tail += size;
            }
            else
            {
                throw new Exception("Buffer overflow in AudioRecorder.cs DataArriced(...)");
            }
        }

        private static void Dispose_m_Recorder()
        {
        }

        #endregion

        #region "Public methods"

        public static void StartRecord()
        {
            if (m_Recorder == null)
            {
                WaveLib.WaveFormat fmt = new WaveLib.WaveFormat(12000, 16, 1);
                m_Recorder = new WaveLib.WaveInRecorder(-1, fmt, 16384, 3, new WaveLib.BufferDoneEventHandler(DataArrived));
            }
        }

        public static void StopRecord()
        {
            if (m_Recorder != null)
            {
                try
                {
                    m_Recorder.Dispose();
                    m_Recorder = null;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

        public static void Rewind()
        {
            m_Tail = 0;
        }

        public static int SaveToStream(Stream aStream)
        {
            aStream.Write(m_Buffer, 0, m_Tail);
            return m_Tail;
        }

        internal static byte[] SaveToBytes()
        {
            byte[] bytes = new byte[m_Tail];
            Buffer.BlockCopy(m_Buffer, 0, bytes, 0, m_Tail);
            return bytes;
        }

        #endregion


    }
}
